package com.h2ospace.yeelight;

import java.io.*;
import java.net.*;

public class main {
    public static void main(String[] args) {
        try {
            final DatagramSocket detectSocket = new DatagramSocket(1982);

            // 发送广播
            new Thread(() ->
            {
                try {
                    int packetPort = 1982;
                    String message = "M-SEARCH * HTTP/1.1\r\nMAN: \"ssdp:discover\"\r\nST: wifi_bulb\r\n";
                    InetAddress hostAddress = InetAddress.getByName("239.255.255.250");
                    DatagramPacket out = new DatagramPacket(message.getBytes(), message.length(), hostAddress, packetPort);
                    detectSocket.send(out);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }).start();

            // 接受广播应答信息
            new Thread(() ->
            {
                while (true) {
                    byte[] buf = new byte[1024];
                    DatagramPacket packet = new DatagramPacket(buf, buf.length);
                    try {
                        System.out.println("-----------------------------------Receive---------------------------");
                        detectSocket.receive(packet);
                        String receive = new String(packet.getData());
                        System.out.println(receive);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }).start();

        } catch (SocketException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
